package com.proxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class VisitanteProxy implements java.lang.reflect.InvocationHandler {

	private Object obj;

	public static Object newInstance(Object obj) {
		return Proxy.newProxyInstance(
				obj.getClass().getClassLoader(), 
				obj.getClass().getInterfaces(),
				new VisitanteProxy(obj));
	}

	private VisitanteProxy(Object obj) {
		this.obj = obj;
	}

	public Object invoke(Object proxy, Method m, Object[] args)
			throws Throwable {
		Object result;
		try {
			Visitante context = (Visitante)obj;
			if(context.isTengoLosPiesLimpios()){
				System.out.println("Tengo los pies limpios, puedo pasar");
				result = m.invoke(obj, args);
			}else{
				result = null;
				System.out.println("No puedo");
			}
		} catch (InvocationTargetException e) {
			throw e.getTargetException();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		} finally {
			System.out.println("Despues de llamar al metodo " + m.getName());
		}
		return result;
	}

	
}